#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdlib.h>
#include "stack.h"

static int init = 0;
static int destroy = 0;

Stack *initStack() {
    //++init;
    //printf("init count:%d\n",init);
    Stack *stack = malloc(sizeof (Stack));
    stack->cp = 0;
    stack->size = STACK_INI_SIZE;
    stack->pool = malloc(STACK_INI_SIZE * sizeof (void *));
    return stack;
}

void releaseStack(Stack *stack) {
    free(stack->pool);
    free(stack);
}

void push(Stack *stack, void *p) {
    if(stack->cp>=stack->size){
        void **tmp = malloc((stack->size+STACK_STEP)*sizeof(void *));
        memcpy(tmp, stack->pool, (stack->size)*sizeof(void *));
        free(stack->pool);
        stack->pool = tmp;
    }
    stack->pool[stack->cp] = p;
    stack->cp+=1;
}

void *pop(Stack *stack) {
    void **tmp = stack->pool;
    void *ret;
    if (stack->cp == 0) {
        return NULL;
    }
    ret = *(tmp  + stack->cp -1);
    --stack->cp;
    return ret;
}

void *getTop(Stack *stack) {
    void **tmp = stack->pool;
    void *ret;
    if (stack->cp == 0) {
        return NULL;
    }
    ret = *(tmp  + stack->cp -1);
    return ret;
}

int stackSize(Stack *stack) {
    return stack->cp;
}

void *getPos(Stack *stack,int pos) {
    void **tmp = stack->pool;
    int cp = 0;
    void *ret;
    int level = pos;
    if (pos >= stack->cp ) {
        return NULL;
    }
    ret = *(tmp  + pos);
    return ret;
}